﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace ExportWordBibModule.SchemaImplementation
{
    /// <summary>
    /// Bibliography source
    /// </summary>
    public class Source
    {
        const string ns = Constants.BibliographyNamespace;
        const string b = Constants.BibliographyPrefix;

        /// <summary>
        /// Gets or sets the book title.
        /// </summary>
        /// <value>The book title.</value>
        public string BookTitle { get; set; }
        /// <summary>
        /// Book authors list
        /// </summary>
        public List<Author> Authors = new List<Author>();

        /// <summary>
        /// Renders the source as XML node.
        /// </summary>
        /// <returns></returns>
        public XmlNode Render()
        {
            // Source
            XmlDocument document = new XmlDocument();
            var sourceNode = document.CreateElement(b, "Source", ns);

            // Tag
            var tag = document.CreateElement(b, "Tag", ns);
            // TODO Need better implementation
            if (BookTitle.Length >= 3)
            {
                tag.InnerText = BookTitle.Substring(0, 3);
            }
            else
            {
                tag.InnerText = BookTitle;
            }
            sourceNode.AppendChild(tag);

            // Source type
            var sourceType = document.CreateElement(b, "SourceType", ns);
            sourceType.InnerText = "Book";
            sourceNode.AppendChild(sourceType);

            // Guid
            var guid = document.CreateElement(b, "Guid", ns);
            guid.InnerText = string.Format("{{{0}}}", Guid.NewGuid().ToString());
            sourceNode.AppendChild(guid);

            // LCID
            var lcid = document.CreateElement(b, "LCID", ns);
            lcid.InnerText = "0";
            sourceNode.AppendChild(lcid);

            // Title
            var bookTitleNode = document.CreateElement(b, "Title", ns);
            bookTitleNode.InnerText = BookTitle;
            sourceNode.AppendChild(bookTitleNode);

            // Authors
            foreach (var author in Authors)
            {

                var authorNode = author.Render();
                var authorNodeImported = document.ImportNode(authorNode, true);
                sourceNode.AppendChild(authorNodeImported);
            }

            return sourceNode;
        }
    }
}
